<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card class="box-card">
            <!-- 添加角色按钮区域 -->
            <el-row class="btn">
                <el-col>
                    <el-button type="primary" @click="addVisible = true">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 角色列表区域 -->
            <el-table :data="rolelist" style="width: 100%" stripe border >
                <!-- 展开列 -->
                <el-table-column type="expand" class="expands">
                  <template slot-scope="scope">
                    <el-row :class="['bdbottom', index === 0 ? 'bdtop' : '','venter']" v-for="(item,index) in scope.row.children" :key="item.id">
                      <!-- 渲染一级权限 -->
                      <el-col :span="5" class="center">
                        <el-tag closable @close="removeRightById(scope.row,item.id)">{{item.authName}}</el-tag>
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                      <!-- 渲染二级和三级权限 -->
                      <el-col :span="19">
                        <!-- 通过for循环嵌套渲染二级权限 -->
                        <el-row :class="[index2 === 0 ? '' : 'bdtop','venter']" v-for="(item2,index2) in item.children" :key="item2.id">
                          <el-col :span="6">
                            <el-tag closable type="success" @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                          </el-col>
                          <el-col :span="18">
                             <!-- 通过for循环嵌套渲染三级权限 -->
                             <el-tag closable type="warning" v-for="item3 in item2.children" :key="item3.id" @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                          </el-col>
                        </el-row>
                      </el-col>
                    </el-row>
                  </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="roleName" label="角色名称" ></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述" ></el-table-column>
                <el-table-column  label="操作" >
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEdit(scope.row.id)">编辑</el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteUser(scope.row.id)">删除</el-button>
                        <el-button type="warning" size="mini" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 添加角色 -->
        <el-dialog title="添加用户" :visible.sync="addVisible" width="50%" @close="addDialogClosed">
            <!-- 内容区域 -->
            <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑修改角色 -->
        <el-dialog title="编辑用户" :visible.sync="editVisible" width="50%" @close="addDialogClosed">
            <!-- 内容区域 -->
            <el-form ref="addFormRef" :model="userObj" :rules="addFormRules" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="userObj.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="userObj.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配权限的对话框 -->
        <el-dialog title="分配权限" :visible.sync="jurisdiction" width="50%" @close="setRightDialogVisible">
          <!-- 树状型控件 -->
          <el-tree :data="jurisdictionList" show-checkbox :props="threeProps" node-key="id"
          default-expand-all :default-checked-keys="defKyes" ref="threeRef"></el-tree>
          <span slot="footer" class="dialog-footer">
            <el-button @click="jurisdiction = false">取 消</el-button>
            <el-button type="primary" @click="allotRights">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  created () {
    this.getRolesList()
  },
  data () {
    return {
      // 所有角色列表数据
      rolelist: [],
      // 添加用户的开关
      addVisible: false,
      // 添加用户的表单数据
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 编辑用户的开关
      editVisible: false,
      // 查询到的用户信息对象
      userObj: {},
      // 控制分配权限对话框的显示与隐藏
      jurisdiction: false,
      // 权限列表
      jurisdictionList: [],
      // 树形控件的属性绑定对象
      threeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值数组
      defKyes: [],
      // 当前即将分配权限的角色
      roleId: ''
    }
  },
  methods: {
    // 获取所有角色的列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取用户角色列表失败')
      this.rolelist = res.data
      console.log(this.rolelist)
    },
    // 添加用户的点击
    async addUser () {
      const { data: res } = await this.$http.post('roles', this.addForm)
      if (res.meta.status !== 201) return this.$message.error('添加用户失败')
      this.$message.success('添加成功')
      this.getRolesList()
      this.addVisible = false
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 展示编辑用户的对话框
    async showEdit (id) {
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error('编辑修改用户失败')
      this.userObj = res.data
      console.log(this.userObj)
      this.editVisible = true
    },
    // 编辑角色列表
    async editUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`roles/${this.userObj.roleId}`, {
          roleName: this.userObj.roleName,
          roleDesc: this.userObj.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error('用户修改失败')
        this.getRolesList()
        this.editVisible = false
        this.$message.success('修改成功')
      })
    },
    // 删除用户
    deleteUser (id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${id}`)
        if (res.meta.status !== 200) {
          this.$message.error('删除失败')
        } else {
          this.$message.success('删除成功')
          this.getRolesList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 根据id删除对应的权限
    async removeRightById (roleId, rightId) {
      // 弹框提示用户是否要删除
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('取消了删除')
      const { data: res } = await this.$http.delete(`roles/${roleId.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('取消权限失败')
      roleId.children = res.data
      this.$message.success('删除权限成功')
    },
    // 展现分配权限的对话框
    async showSetRightDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限数据失败')
      this.jurisdictionList = res.data
      // 递归获取三级节点的ID
      this.getLeafKeys(role, this.defKyes)
      this.jurisdiction = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKyes 数组中
    getLeafKeys (node, arr) {
      // 如果当前node节点不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogVisible () {
      this.defKyes = []
    },
    // 点击为角色分配权限
    async allotRights () {
      const keys = [
        ...this.$refs.threeRef.getCheckedKeys(),
        ...this.$refs.threeRef.getHalfCheckedNodes()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.jurisdiction = false
    }
  }
}
</script>

<style scoped>
.box-card{
    margin-top: 15px;
}
.btn{
    margin-bottom: 15px;
}
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.venter{
  display: flex;
  align-items: center;
}
.center{
  text-align: center;
}
</style>
